//
//  UserAcount.swift
//  SwiftStory
//
//  Created by ZxjMacBookPro on 2020/4/25.
//  Copyright © 2020 ZxjMacBookPro. All rights reserved.
//

import UIKit

@objcMembers
class UserAcount: NSObject, NSCoding {
    var access_token: String?
    var expires_in: Int = 0{
        didSet{
            expires_Date = NSDate(timeIntervalSinceNow: TimeInterval(expires_in))
        }
    }
    var uid: String?
    
    var expires_Date: NSDate?
    
    var avatar_large: String?
    
    var screen_name: String?
    
    
    
    init(dict: [String: Any]) {
        super.init()
        self.setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        NSLog(message: "value \(String(describing: value)) ,key \(key)")
    }
    
    override var description: String{
        let property = ["access_token", "expires_in", "uid", "expires_Date"]
        let dic = dictionaryWithValues(forKeys: property)
        return "\(dic)"
    }
    
    // MARK: - 外部控制
    ///归档
    @discardableResult
    func saveAccount() -> Bool {
        return NSKeyedArchiver.archiveRootObject(self, toFile: UserAcount.filePath)
    }
    
    static var account: UserAcount?
    static let filePath: String = "useracocount.plist".cachesDir()
    ///解归档
    class func loadUserAccount() -> UserAcount? {
        
        if UserAcount.account != nil {
            return UserAcount.account
        }
        
        guard let account = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? UserAcount else {
            return UserAcount.account
        }

        guard let date = account.expires_Date, date.compare(Date()) != ComparisonResult.orderedAscending else{
            NSLog(message: "过期了")
            return nil
        }
            
        UserAcount.account = account
        
        return account
    }
    
    func loadUserInfo(finished: @escaping (_ account: UserAcount?, _ error:Error?)->()){
        
        assert(access_token != nil, "使用该方法必须先授权")
        let path = "2/users/show.json"
        let parameters = ["access_token":access_token!, "uid":uid!]
        
        NetWorkTools.sharInstance.get(path, parameters: parameters, success: { (objc) in
            NSLog(message: "users_show:\(String(describing: objc))")
            let dict = objc as! [String: Any]
            self.avatar_large = dict["avatar_large"] as? String
            self.screen_name = dict["screen_name"] as? String
            finished(self, nil)
        }) { (error) in
            NSLog(message: error)
            finished(nil, error)
        }
        
//        NetWorkTools.sharInstance.get(path, parameters: parameters, progress: { (_) in
//
//        }, success: { (task, objc) in
//            NSLog(message: "users_show:\(objc)")
//            let dict = objc as! [String: Any]
//            self.avatar_large = dict["avatar_large"] as? String
//            self.screen_name = dict["screen_name"] as? String
//            finished(self, nil)
//        }) { (task, error) in
//            NSLog(message: error)
//            finished(nil, error)
//        }
    }
    
    ///是否登录
    class func isLogin() -> Bool{
        return UserAcount.loadUserAccount() != nil
    }
    
    // MARK: - NSCoding
    func encode(with coder: NSCoder) {
        coder.encode(access_token, forKey: "access_token")
        coder.encode(uid, forKey: "uid")
        coder.encode(expires_in, forKey: "expires_in")
        coder.encode(expires_Date, forKey: "expires_Date")
        coder.encode(avatar_large, forKey: "avatar_large")
        coder.encode(screen_name, forKey: "screen_name")
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        self.access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        self.expires_in = aDecoder.decodeInteger(forKey: "expires_in") as Int
        self.uid = aDecoder.decodeObject(forKey: "uid") as? String
        self.expires_Date = aDecoder.decodeObject(forKey: "expires_Date") as? NSDate
        self.avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
        self.screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
        
    }
}

